package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class HotArticleServiceImpl implements HotArticleService {
    @Autowired private ApArticleMapper apArticleMapper;

    /**
     * 计算热点文章
     */
    @Override
    public void computeHotArticle() {
        //1.查询前5天的文章数据, 当前时间     减去五天      转格式
        Date dateParam = DateTime.now().minusDays(5).toDate();
        List<ApArticle> apArticleList = apArticleMapper.findArticleListByLast5days(dateParam);

        //2.计算文章的分值
        List<HotArticleVo> hotArticleVoList = computeHotArticle(apArticleList);    //调用《计算文章分值》方法，hotArticleVoList为有分值的文章

        //3.为每个频道缓存30条分值较高的文章
        cacheTagToRedis(hotArticleVoList);    //调用《为每个频道缓存30条分值较高的文章》方法
    }


    @Autowired private IWemediaClient wemediaClient;
    @Autowired private CacheService cacheService;

    /**
     * 为每个频道缓存30条分值较高的文章
     * hotArticleVoList：已经有了分值的文章
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleVoList) {
        //1、每个频道缓存30条分值较高的文章
        ResponseResult responseResult = wemediaClient.getChannels();    //调用 查询所有频道 方法
        if(responseResult.getCode().equals(200)){
            String channelJson = JSON.toJSONString(responseResult.getData());    //把结果的数据转成json
            List<WmChannel> wmChannels = JSON.parseArray(channelJson, WmChannel.class);    //再把json 转成 WmChannel

            //检索出每个频道的文章
            if(wmChannels != null && wmChannels.size() > 0){
                for (WmChannel wmChannel : wmChannels) {
                    List<HotArticleVo> hotArticleVos = hotArticleVoList.stream().filter(
                            //判断HotArticleVo 表的 ChannelId 和 wmChannel 表的 id 是否一样，一样就表示当前文章属于当前频道的
                            x -> x.getChannelId().equals(wmChannel.getId())).collect(Collectors.toList());

                    //给文章进行排序，取30条分值较高的文章存入redis   key：频道id    value：30条分值较高的文章
                    sortAndCache(hotArticleVos, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + wmChannel.getId());    //调用《排序并且缓存数据》方法
                }}}

        //2、设置推荐数据
        //给文章进行排序，取30条分值较高的文章存入redis  key：频道id   value：30条分值较高的文章
        sortAndCache(hotArticleVoList, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);  //调用《排序并且缓存数据》方法
    }


    /**
     * 排序并且缓存数据
     */
    private void sortAndCache(List<HotArticleVo> hotArticleVos, String key) {
        hotArticleVos = hotArticleVos.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
        if (hotArticleVos.size() > 30) {
            hotArticleVos = hotArticleVos.subList(0, 30);    //截取 0-30 条数据
        }
        cacheService.set(key, JSON.toJSONString(hotArticleVos));    //缓存到redis中
    }


    /**
     * 计算文章分值
     * apArticleList：前五天的文章
     */
    private List<HotArticleVo> computeHotArticle(List<ApArticle> apArticleList) {
        List<HotArticleVo> hotArticleVoList = new ArrayList<>();
        HotArticleVo hot = new HotArticleVo();

        if(apArticleList != null && apArticleList.size() > 0){
            for (ApArticle apArticle : apArticleList) {
                BeanUtils.copyProperties(apArticle, hot);

                Integer score = computeScore(apArticle);   //调用《计算某一文章的具体分值》方法
                hot.setScore(score);    //设置分值
                hotArticleVoList.add(hot);
            }}
        return hotArticleVoList;
    }


    /**
     * 计算某一文章的具体分值
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer scere = 0;

        if(apArticle.getLikes() != null){
            scere += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;    //如果Likes(点赞数量)不为null，权重加 3
        }

        if(apArticle.getViews() != null){
            scere += apArticle.getViews();    //如果Views(阅读数量)不为null，权重加 1
        }

        if(apArticle.getComment() != null){
            scere += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;    //如果Comment(评论数量)不为null，权重加 5
        }

        if(apArticle.getCollection() != null){
            scere += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;    //如果Collection(收藏数量)不为null，权重加 8
        }
        return scere;    //返回分值
    }}